import React, { useState } from 'react'
import { Icon, Upload, message } from 'antd';
import { UploadChangeParam } from 'antd/lib/upload'
import { ReactComponent as AddImageSvg } from '../../../icons/add-image.svg'
import styles from './index.module.scss'
import Viewer from '../../viewer'
import { LocalImage, CheckFileFormat } from '../../../utils/tool/file'

interface PropsInterface {
  onChange: (file: File, localImg: string) => void,
  imgData?: string
}

export default function(props: PropsInterface) {

  const [viewerVisible, setViewerVisible] = useState(false)

  const fileTypes = ['.png', '.jpg', '.jpeg']

  const fileChange = (data: UploadChangeParam) => {
    const file = data.file as any
    if (!CheckFileFormat(file, fileTypes)) {
      message.error('文件格式错误')
      return
    }
    LocalImage(file).then((localImg: string) => {
      props.onChange(file as any, localImg) 
    }).catch((msg: any) => {
      message.error(msg)
    })
  }

  const imageUpStyle: any = {}
  if (props.imgData) {
    imageUpStyle.backgroundImage = `url(${props.imgData})`
  }

  return (
    <div className={ `${styles['com-up-image-base']} w-flex-center` }>
      <Upload
        accept={ fileTypes.join(',') }
        showUploadList={false}
        beforeUpload={ () => false }
        onChange={fileChange}
      >
        <div style={imageUpStyle} className={ `${styles.uploader} w-image-fill` }></div>
      </Upload>
      {
        props.imgData ? 
          <Icon className={ styles.show } type="play-circle" onClick={ () => setViewerVisible(true) } /> 
          : 
          <AddImageSvg className={ styles['add-img'] }></AddImageSvg>
      }
      <Viewer visible={ viewerVisible } images={ props.imgData ? [props.imgData] : [] } onClose={ () => setViewerVisible(false) }></Viewer>
    </div>
  )
}